import { Injectable } from '@nestjs/common';
import { CreateDictDataDto } from './dto/create-dict-data.dto';
import { UpdateDictDataDto } from './dto/update-dict-data.dto';
import { QueryDictDataDto } from './dto/query-dict-data.dto';
import { InjectRepository } from '@nestjs/typeorm';
import { DictData } from './entities/dict-data.entity';
import { Repository } from 'typeorm';
import { Request,Response } from 'express';
import { User } from '../user/entities/user.entity';
import { DeleteDictDataDto } from './dto/delete-dict-data.dto';
import { StatusChangeDto } from 'src/common/baseDto/status-change.dto';
import { Workbook } from 'exceljs';

@Injectable()
export class DictDataService {
  constructor(
    @InjectRepository(DictData)
    private readonly dictDataRepository: Repository<DictData>,
  ) {}

  /**
   * 创建字典数据
   * @param createDictDataDto
   * @param req
   * @returns
   */
  create(createDictDataDto: CreateDictDataDto, req: Request) {
    let user = req.user as User;
    createDictDataDto.create_by = user.username;
    return this.dictDataRepository.save(createDictDataDto);
  }

  /**
   * 获取字典数据列表
   * @param query
   * @returns
   */
  async findAll(query: QueryDictDataDto) {
    let queryBuilder = this.dictDataRepository
      .createQueryBuilder('dictData')
      .where('dictData.dict_type = :dict_type', { dict_type: query.dict_type });
    if (query.dict_label) {
      queryBuilder = queryBuilder.andWhere(
        'dictData.dict_label like :dict_label',
        { dict_label: `%${query.dict_label}%` },
      );
    }
    if (query.status) {
      queryBuilder = queryBuilder.andWhere('dictData.status = :status', {
        status: query.status,
      });
    }

    // 处理分页
    if (!query.pageNum || query.pageNum < 1) {
      query.pageNum = 1;
    }
    if (!query.pageSize || query.pageSize < 1) {
      query.pageSize = 10;
    }
    queryBuilder = queryBuilder
      .groupBy('dictData.dict_code')
      .skip((query.pageNum - 1) * query.pageSize)
      .take(query.pageSize);

    let total = await queryBuilder.getCount();
    let list = await queryBuilder.getMany();
    return {
      pageNum: query.pageNum,
      pageSize: query.pageSize,
      total: total,
      list: list,
    };
  }

  /**
   * 根据字典类型获取字典数据
   * @param dict_type 
   * @returns 
   */
  getDcitData(dict_type: string) {
    return this.dictDataRepository.find({ where: { dict_type: dict_type } });
  }

  /**
   * 获取字典数据详情
   * @param id
   * @returns
   */
  findOne(id: number) {
    return this.dictDataRepository.findOne({ where: { dict_code: id } });
  }

  /**
   * 更新字典数据
   * @param dict_code
   * @param updateDictDataDto
   * @param req
   * @returns
   */
  update(
    dict_code: number,
    updateDictDataDto: UpdateDictDataDto,
    req: Request,
  ) {
    let user = req.user as User;
    updateDictDataDto.dictData.update_by = user.username;
    return this.dictDataRepository.update(
      dict_code,
      updateDictDataDto.dictData,
    );
  }

  /**
   * 更新字典数据状态
   * @param statusChangeDto
   */
  statusChange(statusChangeDto: StatusChangeDto,req: Request,) {
    let user = req.user as User;
    return this.dictDataRepository.update(statusChangeDto.id, {
      status: statusChangeDto.status,
      update_by: user.username,
    });
  }

  /**
   * 删除字典数据
   * @param deleteDictDataDto
   * @returns
   */
  remove(deleteDictDataDto: DeleteDictDataDto) {
    return this.dictDataRepository.delete(deleteDictDataDto.dictDataIds);
  }

  
  /**
   * 导出为表格
   * @param res
   */
  async exportToExcel(res: Response) {
    const workbook = new Workbook();
    const worksheet = workbook.addWorksheet('字典数据');

    worksheet.columns = [
      { header: '字典类型', key: 'dict_type', width: 10 },
      { header: '字典数据ID', key: 'dict_code', width: 10 },
      { header: '字典标签', key: 'dict_label', width: 10 },
      { header: '字典键值', key: 'dict_value', width: 10 },
      { header: '字典排序', key: 'dict_sort', width: 10 },
      { header: '样式属性（其他样式扩展）', key: 'ccs_class', width: 10 },
      { header: '表格回显样式', key: 'list_class', width: 10 },
      { header: '是否默认（Y是 N否）', key: 'is_default', width: 10 },
      { header: '字典状态（0：正常，1：禁用）', key: 'status', width: 10 },
      { header: '创建者', key: 'create_by', width: 10 },
      { header: '创建时间', key: 'create_time', width: 10 },
      { header: '更新者', key: 'update_by', width: 10 },
      { header: '更新时间', key: 'update_time', width: 10 },
      { header: '备注', key: 'remark', width: 10 },
    ];

    const data = await this.dictDataRepository.find();
    worksheet.addRows(data);
    res.setHeader(
      'Content-Type',
      'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
    );
    let filename = encodeURIComponent('字典数据.xlsx'); // 这里中文需要转码
    res.setHeader(
      'Content-Disposition',
      'attachment; filename=' + filename + '',
    );
    res.setHeader('Cache-Control', 'max-age=0');
    const file = await workbook.xlsx.writeBuffer();
    res.end(file);
  }

}
